#include "imageprovider.h"

#include <QPixmap>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QTemporaryFile>
#include <QDir>

#include <QApplication>
#include <QMetaMethod>
#include <QSet>

static QHash<QString, QPixmap> memoryImages;

static ImageProvider *imageProviderInstance = NULL;

ImageProvider &ImageProvider::instance()
{
    if (!imageProviderInstance) {
        imageProviderInstance = new ImageProvider(QApplication::instance());
    }
    return *imageProviderInstance;
}

ImageProvider::ImageProvider(QObject *parent) :
    QObject(parent)
{
    manager = new QNetworkAccessManager(this);

    connect(manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*)));
}

void ImageProvider::requestImage(const QString &multiverseId, QObject *receiver, const char *member)
{
    RequestResponser *rr = new RequestResponser(this, multiverseId, receiver, member);
    QObject::connect(this, SIGNAL(pixmapReady(QString,QPixmap)), rr, SLOT(receivePixmap(QString,QPixmap)));

    if (memoryImages.contains(multiverseId)) {
        emit pixmapReady(multiverseId, memoryImages[multiverseId]);
    }
    else {
        QDir dir = QDir::home();
        dir.cd(".magiqt");
        QString cachePath = dir.filePath(QString("%1.jpeg").arg(multiverseId));

        QUrl url;
        if (QFile::exists(cachePath)) {
            url = QUrl::fromLocalFile(cachePath);
        }
        else {

            if (multiverseId.startsWith("http://")) {
                url = QUrl(multiverseId);
            }
            else {
                QString imageMask("http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=%1&type=card");
                url = QUrl(imageMask.arg(multiverseId));
            }
        }

        QString str = url.toString();

        QNetworkRequest request(url);
        QNetworkReply *replay = manager->get(request);

        replay->setProperty("multiverseId", multiverseId);
    }
}

void ImageProvider::downloadFinished(QNetworkReply *reply)
{
    QString multiverseId = reply->property("multiverseId").toString();
    if (reply->error()) {
//         fprintf(stderr, "Download of %s failed: %s\n",
//                 url.toEncoded().constData(),
//                 qPrintable(reply->errorString()));
    } else {
        QDir dir = QDir::home();
        if (!dir.exists(".magiqt")) {
            dir.mkdir(".magiqt");
        }
        dir.cd(".magiqt");
        QString cachePath = dir.filePath(QString("%1.jpeg").arg(multiverseId));

        QFile cacheFile(cachePath);
        if (cacheFile.exists()) {
            QPixmap p(cacheFile.fileName());
            memoryImages[multiverseId] = p;

            emit pixmapReady(multiverseId, p);
        }
        else if (cacheFile.open(QIODevice::WriteOnly)) {
            cacheFile.write(reply->readAll());
            cacheFile.close();

            QPixmap p(cacheFile.fileName());
            memoryImages[multiverseId] = p;

            emit pixmapReady(multiverseId, p);
        }
        else {
            QTemporaryFile file;
            if (file.open()) {
                file.write(reply->readAll());

                QPixmap p(file.fileName());


                memoryImages[multiverseId] = p;

                emit pixmapReady(multiverseId, p);

                file.close();
            }
        }
    }

    reply->deleteLater();
}
